/*
 * Copyright (c) 2014-2015. Mobiao Group.
 */

package app.controllers;

import app.models.analyze.ProductRecord;
import app.models.member.Member;
import app.models.member.ProfitDetails;
import app.models.product.Product;
import app.models.transfer.TransferProduct;
import bank.BankService;
import bank.resp.AccountAmountRspDto;
import com.google.common.base.Optional;
import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.security.shiro.Securitys;
import org.joda.time.DateTime;

import java.util.List;

/**
 * <p>
 * Default /dashboar Controller.
 * </p>
 */
public class DashboardController extends Controller {

    public void index(){
        if(!Securitys.isLogin()){
            redirect("/login");
            return;
        }
        //产品总数
        setAttr("product_cnt",Product.dao.findAllAvailableCount());
        //会员总数
        setAttr("member_cnt", Member.dao.findAvailableCount());
        //挂单笔数
        setAttr("transfer_product_cnt", TransferProduct.dao.findAvailableCount());
        //投资总数
        setAttr("buy_cnt", ProductRecord.dao.getCountAll());
        //总投资金额
        setAttr("buy_amount_sum", ProductRecord.dao.getSumAmount());
        //发放收益额
        setAttr("profit_sum", ProfitDetails.dao.getSumProfit());
        //总投资人数
        setAttr("buy_person_cnt", ProductRecord.dao.getPersonCount());

        render("/dashboard.ftl");
    }

    /**
     *
     */
    public void dealAmountChat(){
        //平台成交额统计表
        List<ProductRecord> productRecords = ProductRecord.dao.dealAmountChat();
        renderAjaxSuccess(productRecords);
    }

    /**
     * 品牌产品数chat
     */
    public void brandProductChat(){
        List<Product> chat= Product.dao.brandProductChat();
        renderAjaxSuccess(chat);
    }

    /**
     * 发行机构chat
     */
    public void orgProductChat(){
        List<Product> chat= Product.dao.orgProductChat();
        renderAjaxSuccess(chat);
    }

    /**
     * 平台收益发放
     */
    public void profitChat(){
        List<ProfitDetails> profitDetailses = ProfitDetails.dao.profitChat();
        renderAjaxSuccess(profitDetailses);
    }

    @ActionKey("/amount")
    public void amount() {
        final DateTime now = DateTime.now();
        final Optional<AccountAmountRspDto> merchantAccntAmount = BankService.me.getMerchantAccntAmount(now, now);
        if (merchantAccntAmount.isPresent()) {
            if (merchantAccntAmount.get().isSuccess()) {
                renderAjaxSuccess(merchantAccntAmount.get());
                return;
            }
        }
        renderAjaxFailure();
    }

    @ActionKey("/logout")
    public void logout(){
        if(Securitys.isLogin()){
            Securitys.logout();
        }
        redirect("/login");
    }


    /**
     * 心跳检测机制
     */
    @Before(POST.class)
    @ActionKey("/heartbeat")
    public void heartbeat() {


    }
}